/* This file is part of REWise.
 *
 * REWise is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * REWise is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

#include <errno.h>

#include "reader.h"


REWError readBytesInto(FILE * fp, unsigned char * dest, uint32_t size) {
  int ch;
  uint32_t chNo = 0;

  do {
    ch = fgetc(fp);
    dest[chNo] = (unsigned char)ch;
    chNo++;
  } while (ch != EOF && size != chNo);

  if (ch == EOF) {
    return REWERR_EOF;
  }

  return REWERR_OK;
}


REWError readInt32(FILE * fp, int * dest) {
  unsigned char buff[4];
  REWError status;

  // read 4 bytes into the buffer
  status = readBytesInto(fp, buff, 4);

  // failed to read 4 bytes into the buffer
  if (status != REWERR_OK) {
    return status;
  }

  *dest = *(int*)buff;
  return REWERR_OK;
}


REWError readUInt32(FILE * fp, unsigned int * dest) {
  unsigned char buff[4];
  REWError status;

  // read 4 bytes into the buffer
  status = readBytesInto(fp, buff, 4);

  // failed to read 4 bytes into the buffer
  if (status != REWERR_OK) {
    return status;
  }

  *dest = *(unsigned int*)buff;
  return REWERR_OK;
}


REWError readUInt16(FILE * fp, uint16_t * dest) {
  REWError status;
  unsigned char buff[2];

  // read 2 bytes into the buffer
  status = readBytesInto(fp, buff, 2);

  // failed to read 2 bytes into the buffer
  if (status != REWERR_OK) {
    return status;
  }

  *dest = buff[0] + (buff[1] << 8);
  return REWERR_OK;
}


// This will allocate a new string which need to be freed REWERR_OK is returned
REWError readString(FILE * fp, char ** dest) {
  char * string = NULL;
  uint32_t stringLength = 0;
  int ch;
  uint32_t chNo;
  long startOffset = ftell(fp);

  // determine string length
  do {
    ch = fgetc(fp);
    if (ch == EOF) {
      return REWERR_EOF;
    }
    stringLength++;
  } while (ch != 0x00);

  if (ch == EOF) {
    return REWERR_EOF;
  }

  // empty string
  if (stringLength <= 1) {
    return REWERR_OK;
  }

  // allocate string
  string = malloc(sizeof(char) * stringLength + 1);
  if (string == NULL) {
    return REWERR_ERRNO; // failed to allocate mem
  }
  string[stringLength] = 0x00;

  // read the string to the new allocated space
  fseek(fp, startOffset, SEEK_SET);
  chNo = 0;
  do {
    ch = fgetc(fp);
    string[chNo] = (char)ch;
    chNo++;
  } while (ch != 0x00);

  *dest = string;
  return REWERR_OK;
}
